#import "HXPhotoPickerModule.h"
#import <HXPhotoPicker/HXPhotoPicker-Swift.h>
#import <React/RCTUtils.h>

@implementation HXPhotoPickerModule

RCT_EXPORT_MODULE(HXPhotoPickerModule)

- (dispatch_queue_t)methodQueue {
    return dispatch_get_main_queue();
}

RCT_EXPORT_METHOD(openPicker:(NSDictionary *)options
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject) {
    PickerConfiguration *config = [[PickerConfiguration alloc] init];
    config.photoMaxNum = 9;
    config.videoMaxNum = 1;
    
    UIViewController *rootVC = RCTKeyWindow().rootViewController;
    
    [Photo pickerWithConfig:config selectedAssets:nil delegate:nil fromVC:rootVC success:^(PickerResult * _Nonnull result) {
        NSMutableArray *results = [NSMutableArray array];
        for (PhotoAsset *asset in result.photoAssets) {
            [asset getAssetURLWithSuccess:^(NSURL * _Nonnull URL) {
                [results addObject:@{
                    @"uri": URL.absoluteString,
                    @"width": @(asset.imageSize.width),
                    @"height": @(asset.imageSize.height),
                    @"type": asset.mediaType == .video ? @"video" : @"image"
                }];
                
                if (results.count == result.photoAssets.count) {
                    resolve(results);
                }
            } failure:^(NSDictionary * _Nullable info) {
                reject(@"error", @"Failed to get asset URL", nil);
            }];
        }
    } cancel:^{
        reject(@"cancel", @"User cancelled", nil);
    }];
}

@end